package com.yshkj.payment.service.impl;

import com.yshkj.payment.dto.*;
import com.yshkj.payment.entity.medicinal.Medicinal;
import com.yshkj.payment.entity.medicinal.Producer;
import com.yshkj.payment.repository.MedicinalRepository;
import com.yshkj.payment.repository.ProducerRepository;
import com.yshkj.payment.service.MedicinalService;
import com.yshkj.payment.service.impl.operator.MedicinalFormDtoUpdater;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * Created by 唐旭 on 2016/10/2.
 */
@Service
@Transactional
public class MedicinalServiceImpl implements MedicinalService {

    @Autowired
    private MedicinalRepository repository;
    @Autowired
    private ProducerRepository producerRepository;

    @Override
    public void loadList(MedicinalListDto listDto) {
        Page<Medicinal> list = repository.findList(listDto.getQuery(), listDto.toPageable());
        listDto.loadList(list);
        listDto.setState(true);
    }

    @Override
    public DeleteJsonDto delete(String uuid) {
        Medicinal t = new Medicinal();
        t.setUuid(uuid);
        repository.delete(t);
        DeleteJsonDto deleteJsonDto = new DeleteJsonDto();
        deleteJsonDto.setState(true);
        return deleteJsonDto;
    }

    @Override
    public MedicinalFormDto load(String uuid) {
        MedicinalFormDto formDto;
        if (StringUtils.isEmpty(uuid)) {
            formDto = new MedicinalFormDto();
        } else {
            Medicinal one = repository.findOne(uuid);
            formDto = new MedicinalFormDto(one);
        }
        //加载所有的厂商
        List<Producer> all = producerRepository.findAll();
        List<ProducerDto> producerList = formDto.getProducerList();
        for (Producer producer : all) {
            producerList.add(new ProducerDto(producer));
        }
        List<SpecDto> specList = formDto.getSpecList();
        if (specList.isEmpty()) {
            specList.add(new SpecDto());
        }
        formDto.setState(true);
        return formDto;
    }

    @Override
    public CommonJsonDto update(MedicinalFormDto formDto) {
        MedicinalFormDtoUpdater updater = new MedicinalFormDtoUpdater(formDto);
        return updater.update();
    }
}
